<template>
  <el-dialog
    :model-value="dialogFormVisible"
    :title="title"
    align-center
    draggable
    width="43%"
    style="border-radius: 10px; padding: 5px 10px"
  >
    <el-form :model="form" label-width="120px" :rules="rules">
      <el-form-item label="关键事项描述">
        <el-input v-model="form.target" style="width: 410px" />
      </el-form-item>
      <el-form-item label="O分值">
        <el-input v-model="form.totalScore" style="width: 200px" />
      </el-form-item>
      <el-form-item
        v-for="(item, index) in form.keyList"
        :key="index"
        :label="'要求达成的目标' + (index + 1)"
        :prop="'percentList.' + index + '.value'"
      >
        <el-input
          v-model="item.keyResult"
          style="width: 410px; margin-bottom: 10px"
          placeholder="请填写关键结果"
        />
        <el-input
          v-model="item.keyWeight"
          style="width: 200px; margin: 0 10px 10px 0"
          placeholder="考核分数"
        />
        <el-select
          style="width: 200px; margin-bottom: 10px"
          v-model="item.liaEmpId"
          placeholder="执行人员姓名"
          filterable
          remote
          @change="match($event, index)"
        >
          <el-option
            v-for="(item, index) in liaEmpList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          style="width: 200px; margin-bottom: 10px"
          v-model="item.positionId"
          placeholder="执行人员岗位类别"
        >
          <el-option
            v-for="(item, index) in liaEmpPositionList"
            :key="index"
            :label="item.position"
            :value="item.positionId"
          />
        </el-select>
        <el-button
          @click.prevent="removeDomain(item)"
          type="primary"
          icon="Minus"
          circle
          style="margin-left: 20px"
          size="large"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          @click="addDomain"
          type="primary"
          icon="Plus"
          size="large"
          circle
        />
      </el-form-item>
     
      <el-form-item label="考核类型">
        <el-input v-model="form.ins" type="textarea" style="width: 410px" />
      </el-form-item>
	  <el-form-item label="是否启用">
	    <el-switch v-model="form.state" />
	  </el-form-item>
      <el-form-item>
        <el-button style="width: 200px" type="primary" @click="submitForm"
          >确定</el-button
        >
        <el-button style="width: 200px" @click="onClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, onBeforeMount, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { addOkrRule, getKeyList, updateOkrRule } from "@/api/okr";
import { getEmpPositionList } from "@/api/position";
import { getSubordinate } from "@/api/employee";

const form = reactive({
  id: null,
  assessorId: JSON.parse(localStorage.getItem("userInfo")).id,
  totalScore: "",
  target: "",
  keyList: [],
  state: true,
  ins: "",
});

const dialogFormVisible = ref(true);
const props = defineProps({
  KpiDialogVisible: {
    type: Boolean,
    required: true,
  },
  close: {
    type: Function,
    default: () => {},
  },
  update: {
    type: Function,
    default: () => {},
  },
  selectContent: {
    type: Object,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  title: {
    type: String,
    required: true,
  },
});

watch(props, (newValue, oldValue) => {
  let empId = JSON.parse(localStorage.getItem("userInfo")).id;
  getSubordinate(empId).then((data) => {
    liaEmpList.value = [];
    for (let i of data) {
      i.id = String(i.id);
      liaEmpList.value.push(i);
    }
  });

  if (newValue.selectContent != undefined) {
    form.id = newValue.selectContent.okrId;
    form.assessorId = JSON.parse(localStorage.getItem("userInfo")).id;
    form.totalScore = newValue.selectContent.totalScore;
    form.target = newValue.selectContent.target;
    form.ins = newValue.selectContent.ins;
    form.keyList = [];

    if (newValue.type == "add") {
      form.state = newValue.selectContent.state;
      form.keyList.splice(0, form.keyList.length);
      form.keyList[0] = {
        key: 1,
        keyResult: "",
        keyWeight: "",
        liaEmpId: "",
        positionId: "",
      };
    }
    if (newValue.type == "edit") {
      form.state = newValue.selectContent.state == 1 ? true : false;

      let ruleId = newValue.selectContent.okrId;
      getKeyList({ ruleId }).then((data) => {
        form.keyList.splice(0, form.keyList.length);

        for (let i = 0; i < data.data.length; i++) {
          form.keyList.push({
            key: i + 1,
            keyResult: data.data[i].keyResult,
            keyWeight: data.data[i].keyWeight,
            liaEmpId: data.data[i].liaEmpId,
            positionId: data.data[i].positionId,
          });
        }
      });
    }
  }
});

const liaEmpList = ref([]);
onBeforeMount(() => {
  let empId = JSON.parse(localStorage.getItem("userInfo")).id;
  getSubordinate(empId).then((data) => {
    liaEmpList.value = data;
  });
});

const liaEmpPositionList = ref();
const match = (empId, index) => {
  liaEmpPositionList.value = [];
  form.keyList[index].positionId = "";
  getEmpPositionList({ empId }).then((data) => {
    liaEmpPositionList.value = data.data;
  });
};

const removeDomain = (item) => {
  const index = form.keyList.indexOf(item);
  if (index !== -1) {
    form.keyList.splice(index, 1);
  }
};

const addDomain = () => {
  form.keyList.push({
    key: Date.now(),
    keyResult: "",
    keyWeight: "",
    liaEmpId: "",
    positionId: "",
  });
};

const submitForm = () => {
  if (props.type == "add") {
    addOkrRule(form).then((data) => {
      if (data.code == 200) {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        props.close();
        props.update();
      } else {
        ElMessage.error("新增失败");
      }
    });
  } else if (props.type == "edit") {
    updateOkrRule(form).then((data) => {
      if (data.code == 200) {
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        props.close();
        props.update();
      } else {
        ElMessage.error("编辑失败");
      }
    });
  }
};

const onClose = () => {
  props.close();
};

import {
  createRequiredFormRule,
  validateMoney,
  validateScore,
} from "@/utils/rules.js";

const rules = {
  target: [
    createRequiredFormRule("目标不能为空"),
    { validator: validateMoney, trigger: "blur" },
  ],
  totalScore: [
    createRequiredFormRule("0分值不能为空"),
    { validator: validateScore, trigger: "blur" },
  ],
  keyResult: [createRequiredFormRule("关键结果不能为空")],
  keyWeight: [
    createRequiredFormRule("KR权重不能为空"),
    { validator: validateScore, trigger: "blur" },
  ],
  liaEmpId: [createRequiredFormRule("选择责任人不能为空")],
  positionId: [createRequiredFormRule("选择责任人岗位不能为空")],
};
</script>
